package org.jeecg.modules.cascv.image.service.merge.gaowengui;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.service.merge.shengwushiyangui.ShengwushiyanguiJ2kService;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author;作者
 * @Date 2023/2/6 16:31
 * @Description :
 * @Version
 */
@Service
@Slf4j
public class GaowenguiCgService extends ImageService {
    @Value("${imageurl}")
    private String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "TGMTYY1201_09AH_HMRCSAPP2H,6D1DH_27H,6D1DH_27H_UDP";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        if (idsName.contains("UDP")) {
            if (null == LaptopConstant.imageType.get(key)) {
                if (StringUtils.containsIgnoreCase(jsonObject.toString(),"7b0a4845414445525f42595445533d303531323b0a0a46494c454e414d453d3b0a46494c45545950453b0a44494d3d323b0a425954455f4f524445523d6c6974746c655f656e6469616e3b0a545950453d66")) {
                    LaptopConstant.imageType.put(key, 2);
                } else if (StringUtils.containsIgnoreCase(jsonObject.toString(),"7b0a4845414445525f42595445533d303531323b0a0a46494c454e414d453d3b0a46494c45545950453b0a44494d3d323b0a425954455f4f524445523d6c6974746c655f656e6469616e3b0a545950453d66")) {
                    LaptopConstant.imageType.put(key, 1);
                } else {
                    LaptopConstant.imageType.put(key, 3);
                }
            }
            String secondStr = jsonObject.getString("second");
            long second = Long.parseLong(secondStr);
            String subsecond = jsonObject.getString("subsecond");
            secondStr = LaptopUtil.toDayHoursMinSec(second);
            String dataFrames = jsonObject.getString("APED_APDATA_0_2005_1");
            String startEndFlag = jsonObject.getString("APED_APHEAD_6_7_1");
            startEndFlag = startEndFlag.split(";")[0];
            //dataFrames = (dataFrames.split(";")[1]).substring(2).trim();
            if (StringUtils.containsIgnoreCase(dataFrames,"7b0a4845414445525f42595445533d303531323b0a0a46494c454e414d453d3b0a46494c45545950453b0a44494d3d323b0a425954455f4f524445523d6c6974746c655f656e6469616e3b0a545950453d66")) { //是否包含
                dataFrames = dataFrames.substring(1024); //截掉前1024字符
            }
            StringBuilder queue = LaptopConstant.imageData.get(key);
            composite(idsName, key, jsonObject, dataFrames, queue, startEndFlag, secondStr, subsecond);
        } else {


            JSONObject conJson = jsonObject.getJSONObject("Content");

            //打印报错不连续的包序号
            String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
            int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
            Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

            if (null == lastPackageNum) {
                LaptopConstant.packageNumMap.put(key, intpackageNum);
            } else {
                LaptopConstant.packageNumMap.put(key, intpackageNum);
                if (lastPackageNum + 1 != intpackageNum) {
                    if (2511 != lastPackageNum && 0 != intpackageNum) {
                        log.error("图像丢包，包序号不连续，当前包的包序号:" + intpackageNum + "，上一包的包序号:" + lastPackageNum);
                    }
                }
            }
            if (null == LaptopConstant.imageType.get(key)) {
                if (StringUtils.containsIgnoreCase(jsonObject.toString(),"7b0a4845414445525f42595445533d303531323b0a0a46494c454e414d453d3b0a46494c45545950453b0a44494d3d323b0a425954455f4f524445523d6c6974746c655f656e6469616e3b0a545950453d66")) {
                    LaptopConstant.imageType.put(key, 2);
                } else if (StringUtils.containsIgnoreCase(jsonObject.toString(),"7b0a4845414445525f42595445533d303531323b0a0a46494c454e414d453d3b0a46494c45545950453b0a44494d3d323b0a425954455f4f524445523d6c6974746c655f656e6469616e3b0a545950453d66")) {
                    LaptopConstant.imageType.put(key, 1);
                } else {
                    LaptopConstant.imageType.put(key, 3);
                }
            }
            String secondStr = jsonObject.getString("second");
            long second = Long.parseLong(secondStr);
            String subsecond = jsonObject.getString("subsecond");
            secondStr = LaptopUtil.toDayHoursMinSec(second);

            String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
            String startEndFlag = conJson.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));
            startEndFlag = startEndFlag.split(";")[0];
            dataFrames = (dataFrames.split(";")[1]).substring(2).trim();
            // dataFrames =dataFrames.substring(7,dataFrames.length()-10);

            if (StringUtils.containsIgnoreCase(dataFrames,"7b0a4845414445525f42595445533d303531323b0a0a46494c454e414d453d3b0a46494c45545950453b0a44494d3d323b0a425954455f4f524445523d6c6974746c655f656e6469616e3b0a545950453d66")) { //是否包含
                dataFrames = dataFrames.substring(1024); //截掉前1024字符
            }
            StringBuilder queue = LaptopConstant.imageData.get(key);

            composite(idsName, key, conJson, dataFrames, queue, startEndFlag, secondStr, subsecond);
        }
        return null;
    }

    private boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String startEndFlag, String secondStr, String subSecondStr) {
        int width = 3072;
        int height = 1944;
        if (StringUtils.containsIgnoreCase(dataFrames,"7b0a4845414445525f42595445533d303531323b0a0a46494c454e414d453d3b0a46494c45545950453b0a44494d3d323b0a425954455f4f524445523d6c6974746c655f656e6469616e3b0a545950453d")) { //是否包含
            dataFrames = dataFrames.substring(1024); //截掉前1024字符
        }

        if (LaptopConstant.START_FLAG.equalsIgnoreCase(startEndFlag) || !LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {
            if (null == queue) {
                //dataFrames = StringUtils.substring(dataFrames, 16);
                queue = new StringBuilder();
                queue.append(dataFrames);
            } else {
                queue.append(dataFrames);
            }
            LaptopConstant.imageData.put(key, queue);
        } else if (LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {
            while (dataFrames.endsWith("BA")) {//方法用于判断字符串是否以指定后缀结尾
                dataFrames = dataFrames.substring(0, dataFrames.length() - 2);
            }
            queue.append(dataFrames);
            Integer imageType = LaptopConstant.imageType.get(key);
            if (new Integer(2).equals(imageType)) {
                while (queue.length() < 3072 * 1944 * 2 * 2 * 2) {
                    queue.append("0");
                }
                queue = new StringBuilder(queue.substring(0, 3072 * 1944 * 2 * 2 * 2));
            } else {
                while (queue.length() < 3072 * 1944 * 2 * 2) {
                    queue.append("0");
                }
                queue = new StringBuilder(queue.substring(0, 3072 * 1944 * 2 * 2));
            }


            String imgHexStr = queue.toString();
            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                long start = System.currentTimeMillis();
                int[] imgbyte = getGaoWenGuiInt(imgHexStr,key);
                byte[] byteArr = new byte[imgbyte.length];
                for (int i = 0; i < imgbyte.length; i++) {
                    byteArr[i] = (byte) imgbyte[i];
                }
                String idStr = IdWorker.getIdStr();
                Integer writeFlag = LaptopConstant.nativeImageIO.write(byteArr, height, width, "/data/images", idStr + ".png", "png");
                String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                content.put("imageUrl", imageUrl);

                System.out.println("imageUrl = " + imageUrl);
                content.put("idsName", idsName);
                String[] split = secondStr.split(":");
                content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                content.put("key", key);

                log.info("高温柜X射线：" + (System.currentTimeMillis() - start) + "毫秒");
                return content;
            }, taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);

        }

        return true;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("D:\\pc_workspace\\TGMTYY1201_09AH_HMRCSAPP2H.txt");
        GaowenguiCgService gaowenguiCgService = new GaowenguiCgService();

        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            gaowenguiCgService.merge(jsonObject, "TGMTYY1201_09AH_HMRCSAPP2H", "TGMTYY1201_09AH_HMRCSAPP2H");
        }

    }

    public static int to255(long x, long max, long min) {
        Double result = ((x * 1.0 - min * 1.0) / (max * 1.0 - min * 1.0)) * 255.0;
        return result.intValue();
    }


    //去噪点
    public static int[] deleteImageNoise(int[] ints, int num) {
        int[] restlt = new int[ints.length];
        Set<Integer> set = new TreeSet<>();
        for (int i : ints) {
            set.add(i);
        }
        int max = 0;
        int min = 0;
        int i = 1;
        for (Integer temp : set) {
            if (i == num) {
                min = temp;
            }
            if (i == set.size() - num) {
                max = temp;
            }
            i++;
        }
        for (int j = 0; j < ints.length; j++) {
            restlt[j] = ints[j] > max ? max : ints[j];
            restlt[j] = ints[j] < min ? min : ints[j];
        }
        return restlt;
    }


    private int[] getGaoWenGuiInt(String imageStr,String key) {
        List<Long> list = new ArrayList<>();
        if (new Integer(2).equals(LaptopConstant.imageType.get(key))) {//2=亮场图像
            for (int i = 0; i + 8 <= imageStr.length(); i = i + 8) {
                String partStr = imageStr.substring(i, i + 8);
                char[] aChararr = partStr.toCharArray();
                StringBuilder sb1 = new StringBuilder();
                sb1.append(aChararr[4]);
                sb1.append(aChararr[5]);
                sb1.append(aChararr[6]);
                sb1.append(aChararr[7]);
                sb1.append(aChararr[0]);
                sb1.append(aChararr[1]);
                sb1.append(aChararr[2]);
                sb1.append(aChararr[3]);
                list.add(Long.parseLong(sb1.toString(), 16));
            }
        } else {// 1=暗场图像 或 3=实验图像
            for (int i = 0; i + 4 <= imageStr.length(); i = i + 4) {
                String partStr = imageStr.substring(i, i + 4);
                char[] aChararr = partStr.toCharArray();
                StringBuilder sb1 = new StringBuilder();
                sb1.append(aChararr[2]);
                sb1.append(aChararr[3]);
                sb1.append(aChararr[0]);
                sb1.append(aChararr[1]);
                list.add(Long.parseLong(sb1.toString(), 16));
            }
        }

        Long max = null;
        Long min = null;
        for (long temp : list) {
            if (min == null || temp < min) {
                min = temp;
            }
            if (max == null || temp > max) {
                max = temp;
            }
        }

        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            long b = list.get(i);
            ints[i] = to255(b, max, min);
        }

        // 去噪点
        ints = deleteImageNoise(ints, 3);

        return ints;
    }

}
